package com.heima.gateway.filter;

import com.heima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Service
@Slf4j
public class AurhFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        获取请求对象
        ServerHttpRequest request = exchange.getRequest();
//        获取相应对象
        ServerHttpResponse response = exchange.getResponse();
//        请求对象获取访问路径
        String path = request.getURI().getPath();
//        判断是否包含login
        if (path.contains("/login")){
//            放行
            return chain.filter(exchange);
        }
//        不包含 获取请求中的token
        String token = request.getHeaders().getFirst("token");
//        判断token是否为空
        if (StringUtils.isEmpty(token)){
//            为空报401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
//        不为空 获取token的中的请求体
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
//        通过工具类，判断token是否有效
            int result = AppJwtUtil.verifyToken(claimsBody);
            if (result == 0 || result == -1){
//            将userId放入请求头中
                Object userId = claimsBody.get("userId");
                request.mutate().header("userId",userId.toString());

//            有效放行
                return chain.filter(exchange);
            }
        } catch (Exception e) {
//            报错日志
           log.error(e.getMessage());
        }
//        无效报401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    /**
     * 规定执行顺序值越小，越先执行
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
